define(function(require, exports, module) {
    'use strict';

    var rk = require('rk');
    require('../../../xsyBase');



    $.widget('rk.xsySuHeader', $.rk.xsyBase, {
        _create: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            me._beIniting(require('platform/widgets/crm/su/xsySuHeader/initing.tpl'));
            elem.find('.xsy_su_header_grid.xsy_su_header_primary').css('background-color', 'white')

            var data = {
                belongId: me._getCommonData().belongId
            };

            function getHeaderClass(opt) {
                var headerClassMapping = {
                    xsyAccountHeader: 'xsy_header_account',
                    xsyOpportunityHeader : 'xsy_header_opportunity',
                    xsyCustomizeHeader: 'xsy_header_customize'
                }
                return headerClassMapping[opt.widgetType] || 'xsy_header_account';
            }

            me._loadData(data, function(result) {
                var tpl = require('platform/widgets/crm/su/xsySuHeader/widget.tpl');
                opt.headerClass = getHeaderClass(opt);
                var html = rk.templateText(tpl, opt);
                elem.addClass('xsy_su_header').html(html);

                var common = result.common;
                var self = result.self;

                var title = self.title;
                opt.title = title;
                opt.follow = self.follow;
                elem.find('.xsy_su_header_title span[act="title"]').text(title);

                if (opt.follow) {
                    var favButton = elem.find('.xsy_su_header_follow');
                    favButton.removeClass('xsy_su_header_follow').addClass('xsy_su_header_hasfollow');
                    favButton.html('<i></i>已关注');
                    favButton.attr('title', rk.i18n('CRM_CORE_CANCEL_FOLLOW'));
                }



                me._initChildren(); //初始化html中含有wtype的孩子

                if (result) {
                    me._renderCards(result);
                    me._renderToolbar(result);
                }
                me._initPanelScroll();
            });



            //事件监听
            var headerItemName = opt.attributes.titleItem;
            me._listenOuterEvent('detailChanged', function(arg) {
                var itemName = arg.item.entryPropertyNameOnly;
                var newValue = arg.newValue;

                if (arg.item.entryPropertyName == headerItemName) {
                    elem.find('.xsy_su_header_title span[act="title"]').text(newValue);
                }
                var updateEntity = {};
                updateEntity.id = arg.entity.id;
                updateEntity[arg.item.entryPropertyNameOnly] = newValue;

                if(arg.relateComputeItems){
                    updateEntity = $.extend(true, updateEntity, arg.relateComputeItems);
                }
                elem.find('.xsy_su_header_detail').itemsinplace('update', updateEntity);
            });

            me._listenOuterEvent('afterPopupEdit', function(arg) {
                me._loadData({
                    belongId: me._getCommonData().belongId
                }, function(result) {
                    elem.find('.xsy_su_header_detail').itemsinplace('update', result.self.entityData);
                    elem.find('.xsy_su_header_title span[act="title"]').text(result.self.title);
                });
            });

        },


        _initPanelScroll: function() {
            var me = this;
            var opt = me.options;
            var elem = me.element;

            var detail = elem.closest('.xsy_detail'),
                topbar = elem.closest('[data-layout="head"]'),
                approvalBar = topbar.find('.xsy_approval_bar'),
                header = elem,
                headerItems = header.find('.xsy_su_header_sedfields'),
                unFoldMenu = $('#pageleft_unfold');
            var menuFoldClass = 'xsy_su_header_fold_menu_fold',
                menuUnfoldClass = 'xsy_su_header_fold';

            var onScroll = function(info) {

                var appBarHeight = approvalBar.is(':visible') ? approvalBar.outerHeight() : 0;

                if (info.scrollTop <= appBarHeight) {
                    approvalBar.removeClass('outsight');
                    topbar.removeClass([menuFoldClass, menuUnfoldClass].join(' '));
                    headerItems.css('margin-top', 0);
                    detail.css('padding-top', 0);
                } else {
                    if (info.scrollTop <= appBarHeight + headerItems.height()) {
                        detail.css('padding-top', info.scrollTop + header.height());
                    } else {
                        detail.css('padding-top', appBarHeight + headerItems.height() + header.height());
                    }
                    approvalBar.addClass('outsight');
                    topbar.removeClass([menuFoldClass, menuUnfoldClass].join(' ')).addClass(unFoldMenu.is(':visible') ? menuUnfoldClass : menuFoldClass);
                    headerItems.css('margin-top', Math.max(-headerItems.height(), parseInt(appBarHeight - info.scrollTop)));
                }
            }
            me._listenOuterEvent('onCrmPanelScroll', onScroll);

            $(window).on('resize', function(evt) {
                onScroll({
                    scrollTop: detail.scrollParent().scrollTop()
                })
            });

            // return;


            // var detail = elem.find('.xsy_su_header_detail');
            // var fields = detail.find('.xsy_su_header_sedfields');

            // var headerCon = elem.closest('[ data-layout="detail-header"]');

            // var running = false;

            // $(window).on('resize', function() {
            //     if (headerCon.hasClass('xsy_su_header_fold') || headerCon.hasClass('xsy_su_header_fold_menu_fold')) {
            //         if ($('#pageleft_unfold').is(':visible')) {
            //             headerCon.removeClass('xsy_su_header_fold_menu_fold');
            //             headerCon.addClass('xsy_su_header_fold');
            //         } else {
            //             headerCon.removeClass('xsy_su_header_fold');
            //             headerCon.addClass('xsy_su_header_fold_menu_fold');
            //         }
            //     }
            // });

            // //滚动时，header应当悬浮
            // me._listenOuterEvent('onCrmPanelScroll', function(info) { //crm容器的纵向滚动事件
            //     if (info.scrollTop > 100 && (info.scrollBottom > headerCon.outerHeight() || $('#crm-panel')[0].scrollHeight - window.document.body.clientHeight - 55 > headerCon.outerHeight())) {
            //         if (!headerCon.hasClass('xsy_su_header_fold') && !headerCon.hasClass('xsy_su_header_fold_menu_fold')) {
            //             if ($('#pageleft_unfold').is(':visible')) {
            //                 headerCon.addClass('xsy_su_header_fold');
            //             } else {
            //                 headerCon.addClass('xsy_su_header_fold_menu_fold');
            //             }
            //         }

            //         if (detail.data('isfold') != 'true') {
            //             detail.data('isfold', 'true');
            //             if (!running) {
            //                 running = true;
            //                 if (!headerCon.find('div:first').hasClass('xsy_su_header')) {
            //                     headerCon.find('div:first').slideUp(120);
            //                 }
            //                 detail.slideUp(120, function() {
            //                     detail.data('isfold', 'true');
            //                     running = false;
            //                     me._triggerOuterEvent('crmHeaderFloating', {
            //                         height: elem.height()
            //                     });
            //                 });
            //             }
            //         }
            //     } else {
            //         headerCon.removeClass('xsy_su_header_fold');
            //         headerCon.removeClass('xsy_su_header_fold_menu_fold');

            //         if (detail.data('isfold') == 'true') {
            //             detail.data('isfold', 'false');
            //             if (!running) {
            //                 running = true;
            //                 if (!headerCon.find('div:first').hasClass('xsy_su_header') && headerCon.find('div:first').html() != '') {
            //                     headerCon.find('div:first').slideDown(120);
            //                 }
            //                 detail.slideDown(120, function() {
            //                     running = false;
            //                     me._triggerOuterEvent('crmHeaderUnFloating');
            //                 });
            //             }
            //         }
            //     }
            // });
        },
        _renderCards: function(result) {
            var data = result.self;
            var me = this;
            var opt = me.options;
            var elem = me.element;

            var showItems = new Array();

            /* var bannerInfo = data.bannerInfo;
             if(!bannerInfo)return;
             $.each(bannerInfo, function(i, item){
                 var showItem = {};
                 var itemValue = item.itemValue;
                 showItem.title = item.label;
                 showItem.nameOnly = item.nameOnly;

                 if(itemValue && itemValue instanceof Object){
                     showItem.name = itemValue.label;

                     //对公海池字段做特殊处理
                     if(showItem.nameOnly == 'highSeaId'){
                         showItem.remainTimeTip = itemValue.remainTimeTip;
                         showItem.highSeaRules = itemValue.highSeaRules;
                     }

                 }else if(itemValue){
                     showItem.name = itemValue;
                 }
                 showItems.push(showItem);
             });

             var html = rk.templateText(tpl, {items: showItems});
             elem.find('.xsy_su_header_detail').html(html);*/

            elem.find('.xsy_su_header_detail').itemsinplace({
                entities: result.self.entityData,
                items: result.self.itemList,
                evtType: '',
                savesuccess: function(evt, arg) {
                    // arg.element: 触发编辑的DOM元素
                    // arg.item: 编辑的字段
                    // arg.newValue: 保存成功的值
                    // arg.data: 组件当前的全部数据
                    try {
                        //广播一个【外部】事件，控件以外会监听到
                        me._triggerOuterEvent('change', $.extend(arg, {
                            source: 'head'
                        }));
                    } catch (ex) {
                        console.log('trigger detailChanged error: ', ex);
                    }
                },
                buildHtml: function(opt) {
                    var that = this,
                        items = that.items,
                        entities = that.entities;
                    var tpl = require('platform/widgets/crm/su/xsySuHeader/tpl/card.tpl');
                    return template.compile(tpl)({
                        items: items,
                        entities: entities,
                        highSeaInfo: result.self.entityData ? result.self.entityData.highSeaInfo : null
                    });
                }
            })

            elem.find('.xsy_su_header_detail').tooltip({
                items: 'span.js-tip',
                show: false,
                hide: false,
                position: {
                    my: 'left top-20',
                    at: 'right+10 center'
                },
                tooltipClass: 'qtip-dark',
                content: function() {
                    return $.format('<div><span class="arrow_left"></span><div class="tip_text">{#title}</div></div>', {
                        title: $(this).attr("title")
                    });
                }
            });

            elem.find('[wtype="xsyFavouriteButton"]').tooltip({
                items: '[wtype="xsyFavouriteButton"]',
                show: false,
                hide: false,
                position: {
                    my: 'left top-20',
                    at: 'right+10 center'
                },
                tooltipClass: 'qtip-dark',
                content: function() {
                    return $.format('<div><span class="arrow_left"></span><div class="tip_text">{#title}</div></div>', {
                        title: $(this).attr("title")
                    });
                }
            });
        }
    });
});
